package com.tanhua.log.msg;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.pojo.UserLocation;
import com.tanhua.log.domain.AllLog;
import com.tanhua.log.domain.Log;
import com.tanhua.log.domain.LoginLog;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.io.IOException;

@RocketMQMessageListener(consumerGroup = "listenServer", topic = "tanhua-sso-server")
@Component
public class LogAllListener implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String s) {

        try {
            ObjectMapper objectMapper = new ObjectMapper();

            AllLog allLog = objectMapper.readValue(s, AllLog.class);

            Log log = new Log();
            log.setId(ObjectId.get());
            log.setUserId(allLog.getUserId());
            log.setLogTime(allLog.getTime());
            log.setLogeType(allLog.getUri());

            //继续填充剩余数据
            Query query = Query.query(Criteria.where("userId").is(allLog.getUserId()));
            UserLocation one = mongoTemplate.findOne(query, UserLocation.class);
            if (null!=one){
                log.setPlace(one.getAddress());
            }

            mongoTemplate.save(log);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
